#region Copyright(c) 2006 ZO, All right reserved.
// -----------------------------------------------------------------------------
// Copyright(c) 2006 ZO, All right reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   1.  Redistribution of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//   2.  Redistribution in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//   3.  The name of the author may not be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -----------------------------------------------------------------------------
#endregion


#region Using directives

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using ZO.SmartCore.Interop.Windows;

#endregion

namespace ZO.SmartCore.Windows.Forms
{
	/// <summary>
	/// Provides a grouping mechanism for organizing controls. 
	/// </summary>
	[ToolboxBitmap(typeof(Panel))]
	[ToolboxItem(true)]
	public partial class SmartPanel : Panel
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="SmartPanel"/> class.
		/// </summary>
		public SmartPanel()
		{
			InitializeComponent();
		}

		/// <summary>
		/// Releases unmanaged resources and performs other cleanup operations before the
		/// <see cref="T:SmartCore.Windows.Forms.SmartPanel"/> is reclaimed by garbage collection.
		/// </summary>
		~SmartPanel()
		{
			this.Dispose(false);
		}

		private Padding _BorderWidth = new Padding(1);
		private BorderStyle _BorderStyle = BorderStyle.None;
		private RectangleColor _BorderColor = new RectangleColor(SystemColors.ButtonShadow); 

		private bool _Transparent;
		private Timer invalidateTimer;


		/// <summary>
		/// Gets or sets the width of the border.
		/// </summary>
		/// <value>The width of the border.</value>
		[Category("Appearance")]
		[RefreshPropertiesAttribute(RefreshProperties.Repaint)]
		public Padding BorderWidth
		{
			get
			{
				return this._BorderWidth;
			}
			set
			{
				this._BorderWidth = value;
				this.Invalidate();
			}
		}


		/// <summary>
		/// Gets or sets the color of the border.
		/// </summary>
		/// <value>The color of the border.</value>
		[Category("Appearance")]
		[RefreshProperties(RefreshProperties.Repaint)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
		public RectangleColor BorderColor
		{
			get
			{
				return _BorderColor;
			}
			set
			{
				_BorderColor = value;
				this.Invalidate();
			}
		}

		/// <summary>
		/// Gets or sets the border style.
		/// </summary>
		/// <value>The border style.</value>
		[Category("Appearance"), Description("The border style")]
		public new BorderStyle BorderStyle
		{
			get
			{
				return _BorderStyle;
			}
			set
			{
				_BorderStyle = value;
				Invalidate();
			}
		}

		/// <summary>
        /// Gets or sets a value indicating whether this <see cref="SmartPanel"/> is transparent.
		/// </summary>
		/// <value><c>true</c> if transparent; otherwise, <c>false</c>.</value>
		[Category("Appearance")]
		[Description("indicates whether this control is transparent.")]
		[RefreshProperties(RefreshProperties.Repaint)]
		public virtual bool Transparent
		{
			get { return _Transparent; }
			set
			{

				if (this._Transparent != value)
				{
					_Transparent = value;
					SetStyle(ControlStyles.DoubleBuffer, _Transparent);
					this.RecreateHandle();
				}
			}
		}

		/// <summary>
		/// Gets the required creation parameters when the control handle is created.
		/// </summary>
		/// <value></value>
		/// <returns>A <see cref="T:System.Windows.Forms.CreateParams"></see> that contains the required creation parameters when the handle to the control is created.</returns>
		protected override CreateParams CreateParams
		{
			get
			{
				CreateParams parameters = base.CreateParams;

				switch (BorderStyle)
				{
					case BorderStyle.Fixed3D:
						parameters.ExStyle |= (int)ExtendedWindowStyles.StaticEdge;
						break;

					case BorderStyle.FixedSingle:
						parameters.Style |= (int)WindowStyles.Border;
						break;

				}

				if (Transparent)
				{
					parameters.ExStyle |= (int)ExtendedWindowStyles.Transparent;
				}

				return parameters;
			}
		}


		/// <summary>
		/// Gets or sets a value indicating whether this control should redraw its surface using a secondary buffer to reduce or prevent flicker.
		/// </summary>
		/// <value></value>
		/// <returns>true if the surface of the control should be drawn using double buffering; otherwise, false.</returns>
		protected override bool DoubleBuffered
		{
			get
			{
				return base.DoubleBuffered;
			}
			set
			{
				if (Transparent)
				{
					value = false;
				}
				base.DoubleBuffered = value;
			}
		}

		/// <summary>
		/// Paints the background of the control.
		/// </summary>
		/// <param name="pevent">A <see cref="T:System.Windows.Forms.PaintEventArgs"></see> that contains information about the control to paint.</param>
		protected override void OnPaintBackground(PaintEventArgs pevent)
		{
			if (Transparent)
			{
				//do not allow the background to be painted 
			}
			else
			{
				base.OnPaintBackground(pevent);
			}
		}


		/// <summary>
		/// invalidate the parent of the control
		/// </summary>
		private void InvalidateEx()
		{

			if (Parent == null)

				return;

			Rectangle rc = new Rectangle(this.Location, this.Size);

			Parent.Invalidate(rc, true);

		}


		/// <summary>
		/// Initializes the timer.
		/// </summary>
		private void InitializeTimer()
		{
			DestroyTimer();
			if (Transparent)
			{

				invalidateTimer = new Timer();
				invalidateTimer.Interval = 500;

				invalidateTimer.Tick += new EventHandler(invalidateTimer_Tick);

				invalidateTimer.Enabled = true;
			}
		}

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Control.HandleCreated"></see> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnHandleCreated(EventArgs e)
        {
            InitializeTimer();
            base.OnHandleCreated(e);
        }

		/// <summary>
		/// Handles the Tick event of the invalidateTimer control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		private void invalidateTimer_Tick(object sender, EventArgs e)
		{
			this.InvalidateEx();
		}


		/// <summary>
		/// Destroys the timer.
		/// </summary>
		private void DestroyTimer()
		{
			if (this.invalidateTimer != null)
			{
				invalidateTimer.Enabled = false;

				invalidateTimer.Tick -= new EventHandler(invalidateTimer_Tick);

				invalidateTimer.Dispose();
				invalidateTimer = null;
			}
		}

		/// <summary>
		/// Disposes of the resources (other than memory) used by the <see cref="T:System.Windows.Forms.Form"></see>.
		/// </summary>
		/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
		protected override void Dispose(bool disposing)
		{
			if (!IsDisposed)
			{
				try
				{
					//If disposing equals true, dispose all managed 
					// and unmanaged resources.
					if (disposing)
					{
						this.DisposeManagedResources();
						this.DisposeUnmanagedResources();
					}

					else
					{
						this.DisposeUnmanagedResources();
                    }

				}
				catch
				{
					throw;
				}
			}
            base.Dispose(disposing);

		}


		/// <summary>
		/// Override This Method To Dispose Unmanaged Resources.
		/// </summary>
		protected virtual void DisposeManagedResources() { this.DestroyTimer(); }

		/// <summary>
		/// Override This Method To Dispose Managed Resources.
		/// </summary>
		protected virtual void DisposeUnmanagedResources() { }

		/// <summary> 
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
		}

		/// <summary>
		/// Raises the <see cref="E:System.Windows.Forms.Control.Paint"></see> event.
		/// </summary>
		/// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"></see> that contains the event data.</param>
		protected override void OnPaint(PaintEventArgs e)
		{
			Graphics g = e.Graphics;

			switch (this.BorderStyle)
			{
				case BorderStyle.Fixed3D | BorderStyle.FixedSingle | BorderStyle.None:
					break;

				default:
					ControlPaint.DrawBorder(g, this.ClientRectangle, this.BorderColor.Left, this.BorderWidth.Left, (ButtonBorderStyle)this.BorderStyle,
						this.BorderColor.Top, this.BorderWidth.Top, (ButtonBorderStyle)this.BorderStyle,
						this.BorderColor.Right, this.BorderWidth.Right, (ButtonBorderStyle)this.BorderStyle,
						this.BorderColor.Bottom, this.BorderWidth.Bottom, (ButtonBorderStyle)this.BorderStyle);
					break;
			}
			base.OnPaint(e);
		}
	}
}
